package com.monolithiot.sso.service.impl;

import com.monolithiot.sso.common.context.Constants;
import com.monolithiot.sso.common.entity.UserGroup;
import com.monolithiot.sso.common.util.IdentityUtil;
import com.monolithiot.sso.dao.BaseMapper;
import com.monolithiot.sso.dao.mapper.UserGroupMapper;
import com.monolithiot.sso.service.UserGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 2018/12/30 Create by 郭文梁
 * UserGroupServiceImpl
 * 用户组业务行为实现
 *
 * @author 郭文梁
 * @date 2018/12/30
 */
@Slf4j
@Service
public class UserGroupServiceImpl extends BaseServiceImpl<UserGroup> implements UserGroupService {
    private final UserGroupMapper userGroupMapper;

    @Autowired
    public UserGroupServiceImpl(UserGroupMapper userGroupMapper) {
        this.userGroupMapper = userGroupMapper;
    }

    @Override
    BaseMapper<UserGroup> getMapper() {
        return userGroupMapper;
    }

    @Override
    public UserGroup findByIdNumberWithCreator(String idNumber) {
        UserGroup query = new UserGroup();
        query.setIdNumber(idNumber);
        return getMapper().selectOne(query);
    }

    @Override
    public List<UserGroup> searchByNameOrNumber(String w) {
        return userGroupMapper.selectByNumberOrLikeName("%" + w + "%", w);
    }

    @Override
    public UserGroup create(UserGroup userGroup) {
        String idNumber;
        while (checkExistsByIdNumber(idNumber = IdentityUtil.randomNumericString(Constants.DEFAULT_USER_GROUP_ID_NUMBER_LENGTH))) {
            log.debug("Generated idNumber [{}] exists", idNumber);
        }
        userGroup.setIdNumber(idNumber);
        return save(userGroup);
    }

    /**
     * 通过IdNumber判断群组是否存在
     *
     * @param idNumber 号码
     * @return 是否存在
     */
    private boolean checkExistsByIdNumber(String idNumber) {
        UserGroup query = new UserGroup();
        query.setIdNumber(idNumber);
        return userGroupMapper.selectCount(query) > 0;
    }
}
